/**
 * 病种入组病例管理初始化
 */
var SdsQcincase = {
    id: "SdsQcincaseTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    hospID: null,
    checkPerm: $("#formCheck").val(), // 审核权限
    submitPerm: $("#formSubmit").val(), // 填报权限
    docUpPerm: $("#formCheckType").val() // 医生能否直接上报配置
};

/**
 * 初始化表格的列
 */
SdsQcincase.initColumn = function () {
    return [
        {width:30, align: "center", valign: 'middle', sortable: true, formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize=$('#SdsQcincaseTable').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber=$('#SdsQcincaseTable').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {field: 'selectItem', checkbox: true,formatter:function(value,row,index){
                if (SdsQcincase.docUpPerm === "Y") {
                    if(row.state!='Submit'&&row.state!='Check'){
                        return {
                            disabled : true,
                        }
                    }else{
                        return {
                            disabled : false,
                        }
                    }
                } else {
                    if(row.state!='Check'){
                        return {
                            disabled : true,
                        }
                    }else{
                        return {
                            disabled : false,
                        }
                    }
                }

            }},
        /*{title: '单病种', field: 'entityId', width:200, align: 'center', valign: 'middle'},*/
        {title: '病案号', field: 'mrNum', width:120, align: 'center', valign: 'middle'},
        {title: '患者姓名', field: 'name', width:150, align: 'center', valign: 'middle'},
        {title: '科室', field: 'admLocDesc', width:150, align: 'center', valign: 'middle'},
        {title: '主管医师', field: 'admDoctorName', width:150, align: 'center', valign: 'middle'},
        {title: '入组状态', field: 'groupStatusDesc', width:100, align: 'center', valign: 'middle'},
        {title: '填报状态', field: 'fillingStatusDesc', width:100, align: 'center', valign: 'middle'},
        {title: '上报状态', field: 'reportStatusDesc', width:100, align: 'center', valign: 'middle'},
        {title: '迟报天数', field: 'reportDelayDays', width:100, align: 'center', valign: 'middle', formatter:function(value,row,index){
                if (3<=value&&value<5) {
                    return "<div style='background-color:#f0ad4e;'>"+value+"</div>";
                } else if(5<=value&&value<7){
                    return "<div style='background-color:#d9534f;'>"+value+"</div>";
                } else if(7<=value){
                    return "<div style='background-color:#9f4ef0;'>"+value+"</div>";
                } else {
                    return value;
                }
        }},
        {title: '入院日期', field: 'admDate', width:120, align: 'center', valign: 'middle'},
        {title: '出院日期', field: 'dishDate', width:120, align: 'center', valign: 'middle'},
        {title: '入单日期', field: 'inDate', width:120, align: 'center', valign: 'middle'},
        {title: '操作', field: 'id', align: 'center', width: '120px', valign: 'middle',formatter:function(value,row,index){
                var _html = '<a href="javascript:SdsQcincase.edit(\''+row.id+'\')" title="填报"><i class="hisui-icon icon-write-order"></i></a>';
                _html += '<a href="javascript:SdsQcincase.del(\''+row.id+'\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
                _html += '<a href="javascript:SdsQcincase.upload(\''+row.id+'\')" title="上报"><i class="hisui-icon icon-upload-cloud"></i></a>';
                _html += '<a href="javascript:SdsQcincase.record(\''+row.id+'\',\''+row.mrNum+'\',\''+row.name+'\')" title="日志"><i class="hisui-icon icon-clock-record"></i></a>';
                return _html;
            }}];
};

/**
 * 检查是否选中
 */
SdsQcincase.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Sys.info("请先选中表格中的某一记录！");
        return false;
    }else{
        SdsQcincase.seItem = selected[0];
        return true;
    }
};

/**
 * 点击新增病种入组病例
 */
SdsQcincase.add = function () {
    var index = Sys.open('新增病种入组病例',Sys.backendPath + '/sds/sdsqcincase/to_add',['800px', '420px']);
    this.layerIndex = index;
};

/**
 * 打开查看病种入组病例详情
 */
SdsQcincase.edit = function (id) {
	var flag = false;
	if(id){
		flag = true;
	}else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
	if (flag) {
    	var index = Sys.open('病种入组病例详情',Sys.backendPath + '/sds/sdsqcformshow?mrListId=' + id );
        this.layerIndex = index;
    }
};

/**
 * 删除病种入组病例
 */
SdsQcincase.del = function (id) {
	var flag = false;
	if(id){
		flag = true;
	}else if (this.check()) {
        id = this.seItem.id;
        name = this.seItem.name
        flag = true;
    }
	if (flag) {
        var operation = function(){
	        var ajax = new $ax(Sys.backendPath + "/sds/sdsqcincase/delete", function (data) {
	            Sys.success("删除成功!");
	            SdsQcincase.table.refresh();
	        }, function (data) {
	            Sys.error("删除失败!" + data.responseJSON.message + "!");
	        });
            var params = {};
            params.mrListId = id;
            ajax.setData(params);
            ajax.start();
	    };
	    Sys.confirm("是否删除病种入组病例?",operation);
    }
};

/**
 * 单病种上报
 */
SdsQcincase.upload = function (id) {
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var ajax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/upload/" + id, function (UpRet) {
        $.messager.progress("close")
        if (UpRet.code==1) {
            $.messager.popover({msg: '上传成功！',type:'success',timeout: 1000})
            //更新状态
            var ax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '状态更新成功！',type:'success',timeout: 1000})
                SdsQcincase.search1();
            }, function (data) {
                $.messager.alert("错误提示", "状态更新错误!", 'info');
            });
            // 如果返回信息Code为“1”，且无message信息，则说明前置机该病种为测试状态，将该入组记录加个测试上报标识
            if (UpRet.message==null||UpRet.message=="") {
                ax.set('testFlg', 1);
            }
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.start();
        }else if(UpRet.message.indexOf('病案号重复')>0){
            //更新状态
            var ax = new $ax(Sys.backendPath + "/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '已存在上传记录，状态更新成功！',type:'success',timeout: 1000})
                SdsQcincase.search1();
            }, function (data) {
                $.messager.alert("错误提示", "已存在上传记录，状态更新错误!", 'info');
            });
            ax.set('mrListId', id);
            ax.set('status', 'Up');
            ax.set('reason', '');
            ax.set('resume', '');
            ax.start();
        }else{
            $.messager.alert("错误提示", "表单上传失败!Error=" + UpRet.message, 'info');
        }
    }, function (data) {
        $.messager.alert("错误提示", "表单上传失败!", 'info');
    });
    ajax.setAsync();
    ajax.start();
}

/**
 * 打开查看病例操作记录
 */
SdsQcincase.record = function (id, mrno, name) {
    var flag = false;
    if(id){
        flag = true;
    }else if (this.check()) {
        id = this.seItem.id;
        flag = true;
    }
    if (flag) {
        var index = Sys.open('【填报审核操作日志】姓名：'+name+' 病案号：'+mrno,Sys.backendPath + '/sds/sdsqcincaseoperlog/' + id,['800px','420px']);
        this.layerIndex = index;
    }
};

/**
 * 查询病种入组病例列表
 */
SdsQcincase.search1 = function () {
    var dateType = $('#dateType2').combobox('getValue');//结束日期
    var startDate = $('#startDate2').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate2').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    SdsQcincase.getQcincaseByDate(dateType, startDate, endDate)
};

SdsQcincase.search2 = function () {
    var dateType = $('#dateType1').combobox('getValue');//查询日期
    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    var fillStatus = $('#fillStatus').combobox('getValue');
    var reportStatus = $('#reportStatus').combobox('getValue');
    var groupStatus = $('#groupStatus').combobox('getValue');
    var recordNumber = $("#recordNumber").val();
    var name = $("#name").val();
    var dept = $("#dept").val();
    var doctor = $("#doctor").val();
    var QCEntityAbbrev = $("#abbrev").val();

    SdsQcincase.search(dateType, startDate, endDate, fillStatus, reportStatus, groupStatus, recordNumber, name, dept, doctor, QCEntityAbbrev, "");
};

SdsQcincase.search = function (dateType, startDate, endDate, fillStatus, reportStatus, groupStatus, recordNumber, name, dept, doctor, QCEntityAbbrev, searchType) {
    var queryData = {};
    queryData['dateType'] = dateType;
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['fillingStatus'] = fillStatus;
    queryData['reportStatus'] = reportStatus;
    queryData['groupStatus'] = groupStatus;
    queryData['mrNum'] = recordNumber;
    queryData['name'] = name;
    queryData['admLocDesc'] = dept;
    queryData['admDoctorName'] = doctor;
    queryData['abbrev'] = QCEntityAbbrev;
    queryData['searchType'] = searchType;
    SdsQcincase.table.refresh({query: queryData});
};

SdsQcincase.qcFormShow = function(r, e, f) {
    var index = Sys.open('病种入组病例详情',Sys.backendPath + '/sds/sdsqcformshow?mrListId=' + r.id );
    this.layerIndex = index;
}

$("#btnShowEntiy").on('click',function(){
    $HUI.dialog('#winQCEntity').open();
});

$("#btnBatchUp").on('click',function(){
    var selectRows = $("#SdsQcincaseTable").bootstrapTable('getSelections');
    if (selectRows.length == 0) {
        Sys.error("请选择要上报的病例！");
        return;
    }
    for (var i=0,l=selectRows.length;i<l;i++) {
        var row = selectRows[i];
        SdsQcincase.upload(row.id);
    }
});

SdsQcincase.LoadItemSta = function(QCEntiyID,QCEntiyDesc,QCEntityAbbrev, status){
    var dateType = $('#dateType2').combobox('getValue');
    var startDate = $('#startDate2').datebox('getValue');//开始日期
    var endDate = $('#endDate2').datebox('getValue');//结束日期

    $('#dateType1').combobox('setValue', dateType);
    $('#startDate1').datebox('setValue', startDate);
    $('#endDate1').datebox('setValue', endDate);
    $('#abbrev').val(QCEntityAbbrev);

   /* var str = $('#entityName').attr('data-options');
    var o = str.split(',')
    var index = o.indexOf("title:''")
    o.splice(index,1,"title:'"+QCEntiyDesc+"'")
    console.log(o.join(','))
    var res = o.join(',')
    $('#entityName').attr('data-options', res);*/
    /*var temp = $('#entityName').layout('panel','center');
    temp.panel('setTitle',QCEntiyDesc);*/
    $('#entityName').panel({title: QCEntiyDesc})

    SdsQcincase.search(dateType, startDate, endDate, "", "", "", "", "", "", "", QCEntityAbbrev, status);

    $HUI.dialog('#winQCEntity').close();


}


//指标统计数据
SdsQcincase.getQcincaseByDate = function(dateType, startDate, endDate){
    //加载病种显示
    var ajax = new $ax(Sys.backendPath + "/sds/sdsqcincase/qryQCEntity", function (data) {
        var dicList = data[0].sdsQcentityEntities
        var len = dicList.length,columns=4,listHtml="<div style='height: 500px;overflow:scroll'>"
        //查询报告份数渲染
        var num = data.length
        if(num == 1 && data[0].id == ""){
            num = 0;
        }
        $("#entityNum").html(num)
        var per = Math.round((1/columns) * 90) + '%';   //每列所在百分比
        var count = parseInt(len/columns)+1;
        for (var index =0; index< count; index++) {
            var listlen = (((index+1)*columns)<len) ? (index+1)*columns : len;
            listHtml += "<div style='padding:10px'>";
            for (var dicIndex = index*columns; dicIndex < listlen; dicIndex++) {
                var dicSubList = dicList[dicIndex];
                listHtml += " <div style='border:1px solid #ccc;padding:10px;margin-right: 10px;float:left;width:250px; border-radius: 5px;'>";
                if (dicSubList.isActive == 2) { // 测试病种标识
                    if (dicSubList.testCount >= 20) {
                        listHtml += " <p style='margin: 5px 0 10px 0;'>"+" "+dicSubList.btDesc+"&nbsp;<img src='/static/common/img/sds/test.png'>&nbsp;<span style='color: #ff0000'>已上报超20例！</span></p>";
                    } else {
                        listHtml += " <p style='margin: 5px 0 10px 0;'>"+" "+dicSubList.btDesc+"&nbsp;<img src='/static/common/img/sds/test.png'></p>";
                    }
                } else {
                    listHtml += " <p style='margin: 5px 0 10px 0;'>"+" "+dicSubList.btDesc+"</p>";
                }
                listHtml += " <img style='float: left;border-radius: 10px;' width='50px'  height='50px' src='/static/common/img/sds/"+dicSubList.abbrev+".png'/>";

                if (SdsQcincase.docUpPerm === "Y") {
                    listHtml += " <div style='float: left;margin-left: 15px;'>";
                    listHtml += " <p style='margin:0 0 10px 0;'>待填报：<a style='cursor:pointer' onClick='SdsQcincase.LoadItemSta("+dicSubList.id+",\""+dicSubList.btDesc+"\",\""+dicSubList.abbrev+"\",\"notReported\")'><span>"+dicSubList.notReported+"</span></a></p>";
                    listHtml += " <p style='margin: 0;'>已上报：<span>"+dicSubList.reported+"</span></p>";
                    listHtml += " </div>";
                } else {
                    if (SdsQcincase.submitPerm === "1") {
                        listHtml += " <div style='float: left;margin-left: 15px;'>";
                        listHtml += " <p style='margin:0 0 10px 0;'>待填报：<a style='cursor:pointer' onClick='SdsQcincase.LoadItemSta("+dicSubList.id+",\""+dicSubList.btDesc+"\",\""+dicSubList.abbrev+"\",\"notReported\")'><span>"+dicSubList.notReported+"</span></a></p>";
                        listHtml += " <p style='margin: 0;'>已上报：<span>"+dicSubList.reported+"</span></p>";
                        listHtml += " </div>";
                    }
                    if (SdsQcincase.checkPerm === "1") {
                        listHtml += " <div style='float: left;margin-left: 15px;'>";
                        listHtml += " <p style='margin:0 0 10px 0;'>待审核：<a style='cursor:pointer' onClick='SdsQcincase.LoadItemSta(" + dicSubList.id + ",\"" + dicSubList.btDesc + "\",\"" + dicSubList.abbrev + "\",\"notChecked\")'><span>" + dicSubList.notChecked + "</span></a></p>";
                        listHtml += " <p style='margin: 0;'>已审核：<a style='cursor:pointer' onClick='SdsQcincase.LoadItemSta(" + dicSubList.id + ",\"" + dicSubList.btDesc + "\",\"" + dicSubList.abbrev + "\",\"checked\")'><span>" + dicSubList.checked + "</span></a></p>";
                        listHtml += " </div>";
                    }
                }
                listHtml += " </div>";
            }
            listHtml += "</div>"
            listHtml += "<div style='clear:both'></div>"
        }
        listHtml += "</div>"
        $('#QCEntityList').html(listHtml);
        /*$.parser.parse('#QCEntityList');  //解析checkbox*/
    }, function (data) {
        Sys.info("查询失败！");
        return false;
    });
    ajax.set("dateType",dateType);
    ajax.set("startDate",startDate);
    ajax.set("endDate",endDate);
    ajax.start();
}

$(function () {
    $('#winQCEntity').dialog({
        title: '病种统计',
        closable: false,
        modal: true
    });

    var dateType = $('#dateType2').combobox('getValue');
    debugger
    var startDate = $('#startDate2').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate2').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    SdsQcincase.getQcincaseByDate(dateType, startDate, endDate)

    var defaultColunms = SdsQcincase.initColumn();
    var table = new BSTable(SdsQcincase.id, Sys.backendPath + "/sds/sdsqcincase/list", defaultColunms);
    table.setPaginationType("server");
    table.setPageSize(10);
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setShowToggle(false);
    table.setShowExport(false);
    var b_height = document.documentElement.clientHeight;
    table.setHeight(b_height-55);
    table.setOnDblClickRow(SdsQcincase.qcFormShow); //双击数据行打开表单填报
    SdsQcincase.table = table.init();
});

//在Jquery里格式化Date日期时间数据
function timeStamp2String(time){
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}
